package org.example.gan.test;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

/**
 * @Author: luyg
 * @Date: 2024/08/27/21:40
 * @Description:
 */
@Configuration
public class DelayedBeanInitializationConfig {

    @Bean
    @Primary
    public static BeanFactoryPostProcessor beanFactoryPostProcessor() {
        //在spring实例化所有bean之前，将除了leaderSelector之外的所有bean设置成懒加载
        return new BeanFactoryPostProcessor() {
            @Override
            public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
                // 将Bean设置为非自动初始化
                for (String beanName : beanFactory.getBeanDefinitionNames()) {
                    if (!beanName.contains("leaderLatch")) {
                        beanFactory.getBeanDefinition(beanName).setLazyInit(true);
                    }
                }
            }
        };
    }
}
